package com.tju.ocean_ecology_website.controller;

import com.tju.ocean_ecology_website.dto.ApiResponse;
import com.tju.ocean_ecology_website.dto.MemberInviteDTO;
import com.tju.ocean_ecology_website.dto.MemberQueryDTO;
import com.tju.ocean_ecology_website.dto.MemberRejectDTO;
import com.tju.ocean_ecology_website.dto.PageResult;
import com.tju.ocean_ecology_website.dto.TeamMemberDTO;
import com.tju.ocean_ecology_website.entity.TeamMember;
import com.tju.ocean_ecology_website.entity.User;
import com.tju.ocean_ecology_website.service.TeamMemberService;
import com.tju.ocean_ecology_website.service.UserService;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import jakarta.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 成员管理控制器
 */
@RestController
@RequestMapping("/api")
public class MembersController {

    @Resource
    private TeamMemberService teamMemberService;

    @Resource
    private UserService userService;

    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 获取成员列表
     *
     * @param queryDTO 查询参数
     * @return 成员列表
     */
    @GetMapping("/members")
    public ResponseEntity<ApiResponse<PageResult<TeamMemberDTO>>> getMemberList(MemberQueryDTO queryDTO) {
        // 创建成员筛选条件
        TeamMember memberQuery = new TeamMember();

        if (queryDTO.getTeamId() != null) {
            memberQuery.setTeamId(queryDTO.getTeamId());
        }

        if (queryDTO.getRole() != null) {
            memberQuery.setRole(queryDTO.getRole());
        }

        if (queryDTO.getStatus() != null) {
            memberQuery.setStatus(queryDTO.getStatus());
        }

        if (queryDTO.getAuditStatus() != null) {
            memberQuery.setAuditStatus(queryDTO.getAuditStatus());
        }

        // 查询成员数据
        PageRequest pageRequest = queryDTO.toPageRequest();
        Page<TeamMember> memberPage = teamMemberService.queryByPage(memberQuery, pageRequest);

        // 构建成员DTO列表
        List<TeamMemberDTO> memberDTOs = new ArrayList<>();
        for (TeamMember member : memberPage.getContent()) {
            // 查询用户信息
            User user = userService.queryById(member.getUserId());

            // 构建DTO
            TeamMemberDTO dto = TeamMemberDTO.fromUserAndTeamMember(user, member);

            // 如果有姓名查询条件，进行过滤
            if (queryDTO.getName() != null && !queryDTO.getName().isEmpty()) {
                if (dto.getName() == null || !dto.getName().contains(queryDTO.getName())) {
                    continue;
                }
            }

            memberDTOs.add(dto);
        }

        // 创建分页结果
        Page<TeamMemberDTO> dtoPage = new PageImpl<>(memberDTOs, pageRequest, memberPage.getTotalElements());
        PageResult<TeamMemberDTO> pageResult = PageResult.fromPage(dtoPage, queryDTO.getPage());

        return ResponseEntity.ok(ApiResponse.success(pageResult));
    }

    /**
     * 获取成员详情
     *
     * @param id 成员ID
     * @return 成员详情
     */
    @GetMapping("/members/{id}")
    public ResponseEntity<ApiResponse<TeamMemberDTO>> getMemberDetail(@PathVariable("id") Long id) {
        TeamMember member = teamMemberService.queryById(id);
        if (member == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "成员不存在"));
        }

        // 查询用户信息
        User user = userService.queryById(member.getUserId());

        // 构建DTO
        TeamMemberDTO dto = TeamMemberDTO.fromUserAndTeamMember(user, member);

        return ResponseEntity.ok(ApiResponse.success(dto));
    }

    /**
     * 添加成员
     *
     * @param member 成员信息
     * @return 添加结果
     */
    @PostMapping("/members")
    public ResponseEntity<ApiResponse<TeamMemberDTO>> addMember(@RequestBody TeamMember member) {
        // 设置默认值
        member.setJoinTime(new Date());
        member.setStatus(0); // 活跃
        member.setAuditStatus(0); // 待审核

        // 保存成员
        TeamMember savedMember = teamMemberService.insert(member);

        // 查询用户信息
        User user = userService.queryById(savedMember.getUserId());

        // 构建DTO
        TeamMemberDTO dto = TeamMemberDTO.fromUserAndTeamMember(user, savedMember);

        return ResponseEntity.ok(ApiResponse.success(dto, "添加成员成功"));
    }

    /**
     * 更新成员
     *
     * @param id 成员ID
     * @param member 成员信息
     * @return 更新结果
     */
    @PutMapping("/members/{id}")
    public ResponseEntity<ApiResponse<TeamMemberDTO>> updateMember(
            @PathVariable("id") Long id,
            @RequestBody TeamMember member) {

        // 查询成员信息
        TeamMember existingMember = teamMemberService.queryById(id);
        if (existingMember == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "成员不存在"));
        }

        // 设置ID
        member.setId(id);

        // 保留原有的审核状态和拒绝原因
        member.setAuditStatus(existingMember.getAuditStatus());
        member.setRejectReason(existingMember.getRejectReason());

        // 更新成员
        TeamMember updatedMember = teamMemberService.update(member);

        // 查询用户信息
        User user = userService.queryById(updatedMember.getUserId());

        // 构建DTO
        TeamMemberDTO dto = TeamMemberDTO.fromUserAndTeamMember(user, updatedMember);

        return ResponseEntity.ok(ApiResponse.success(dto, "更新成员成功"));
    }

    /**
     * 删除成员
     *
     * @param id 成员ID
     * @return 删除结果
     */
    @DeleteMapping("/members/{id}")
    public ResponseEntity<ApiResponse<Void>> removeMember(@PathVariable("id") Long id) {
        // 查询成员信息
        TeamMember member = teamMemberService.queryById(id);
        if (member == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "成员不存在"));
        }

        // 删除成员
        boolean result = teamMemberService.deleteById(id);

        if (result) {
            return ResponseEntity.ok(ApiResponse.success(null, "删除成员成功"));
        } else {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "删除成员失败"));
        }
    }

    /**
     * 审核通过成员
     *
     * @param id 成员ID
     * @return 审核结果
     */
    @PostMapping("/members/{id}/approve")
    public ResponseEntity<ApiResponse<TeamMemberDTO>> approveMember(@PathVariable("id") Long id) {
        TeamMember member = teamMemberService.approveMember(id);
        if (member == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "成员不存在"));
        }

        // 查询用户信息
        User user = userService.queryById(member.getUserId());

        // 构建DTO
        TeamMemberDTO dto = TeamMemberDTO.fromUserAndTeamMember(user, member);

        return ResponseEntity.ok(ApiResponse.success(dto, "审核通过成功"));
    }

    /**
     * 拒绝成员申请
     *
     * @param id 成员ID
     * @param rejectDTO 拒绝信息
     * @return 拒绝结果
     */
    @PostMapping("/members/{id}/reject")
    public ResponseEntity<ApiResponse<TeamMemberDTO>> rejectMember(
            @PathVariable("id") Long id,
            @Valid @RequestBody MemberRejectDTO rejectDTO) {

        TeamMember member = teamMemberService.rejectMember(id, rejectDTO.getReason());
        if (member == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "成员不存在"));
        }

        // 查询用户信息
        User user = userService.queryById(member.getUserId());

        // 构建DTO
        TeamMemberDTO dto = TeamMemberDTO.fromUserAndTeamMember(user, member);

        return ResponseEntity.ok(ApiResponse.success(dto, "拒绝成员申请成功"));
    }

    /**
     * 发送邀请
     *
     * @param inviteDTO 邀请信息
     * @return 邀请结果
     */
    @PostMapping("/members/invite")
    public ResponseEntity<ApiResponse<Map<String, String>>> sendInvitation(
            @Valid @RequestBody MemberInviteDTO inviteDTO) {

        String inviteCode = teamMemberService.sendInvitation(
                inviteDTO.getTeamId(),
                inviteDTO.getEmail(),
                inviteDTO.getRole(),
                inviteDTO.getMessage()
        );

        Map<String, String> result = new HashMap<>();
        result.put("inviteCode", inviteCode);

        return ResponseEntity.ok(ApiResponse.success(result, "发送邀请成功"));
    }

    /**
     * 获取邀请链接
     *
     * @param teamId 团队ID
     * @return 邀请链接
     */
    @GetMapping("/members/invite-link")
    public ResponseEntity<ApiResponse<Map<String, String>>> getInviteLink(
            @RequestParam("teamId") Long teamId) {

        String inviteLink = teamMemberService.getInviteLink(teamId);

        Map<String, String> result = new HashMap<>();
        result.put("inviteLink", inviteLink);

        return ResponseEntity.ok(ApiResponse.success(result));
    }

    /**
     * 导出成员信息
     *
     * @param queryDTO 查询参数
     * @return Excel文件
     */
    @GetMapping("/members/export")
    public ResponseEntity<byte[]> exportMembers(MemberQueryDTO queryDTO) {
        // 创建成员筛选条件
        TeamMember memberQuery = new TeamMember();

        if (queryDTO.getTeamId() != null) {
            memberQuery.setTeamId(queryDTO.getTeamId());
        }

        if (queryDTO.getRole() != null) {
            memberQuery.setRole(queryDTO.getRole());
        }

        if (queryDTO.getStatus() != null) {
            memberQuery.setStatus(queryDTO.getStatus());
        }

        if (queryDTO.getAuditStatus() != null) {
            memberQuery.setAuditStatus(queryDTO.getAuditStatus());
        }

        // 查询成员数据
        List<TeamMember> members = teamMemberService.exportMembers(memberQuery);

        // 创建Excel文件
        try {
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("成员信息");

            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] headers = {"姓名", "用户名", "角色", "状态", "审核状态", "加入时间", "邮箱", "电话"};

            // 设置标题样式
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);

            // 填充标题
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
                sheet.autoSizeColumn(i);
            }

            // 填充数据
            int rowNum = 1;
            for (TeamMember member : members) {
                // 查询用户信息
                User user = userService.queryById(member.getUserId());
                if (user == null) continue;

                // 如果有姓名查询条件，进行过滤
                if (queryDTO.getName() != null && !queryDTO.getName().isEmpty()) {
                    if (user.getName() == null || !user.getName().contains(queryDTO.getName())) {
                        continue;
                    }
                }

                Row row = sheet.createRow(rowNum++);

                row.createCell(0).setCellValue(user.getName() != null ? user.getName() : "");
                row.createCell(1).setCellValue(user.getUsername() != null ? user.getUsername() : "");

                String role = "";
                if (member.getRole() != null) {
                    switch (member.getRole()) {
                        case 0:
                            role = "领导者";
                            break;
                        case 1:
                            role = "管理员";
                            break;
                        case 2:
                            role = "普通成员";
                            break;
                        default:
                            role = "未知";
                    }
                }
                row.createCell(2).setCellValue(role);

                String status = "";
                if (member.getStatus() != null) {
                    switch (member.getStatus()) {
                        case 0:
                            status = "活跃";
                            break;
                        case 1:
                            status = "非活跃";
                            break;
                        default:
                            status = "未知";
                    }
                }
                row.createCell(3).setCellValue(status);

                String auditStatus = "";
                if (member.getAuditStatus() != null) {
                    switch (member.getAuditStatus()) {
                        case 0:
                            auditStatus = "待审核";
                            break;
                        case 1:
                            auditStatus = "已通过";
                            break;
                        case 2:
                            auditStatus = "已拒绝";
                            break;
                        default:
                            auditStatus = "未知";
                    }
                }
                row.createCell(4).setCellValue(auditStatus);

                row.createCell(5).setCellValue(member.getJoinTime() != null ? dateFormat.format(member.getJoinTime()) : "");
                row.createCell(6).setCellValue(user.getEmail() != null ? user.getEmail() : "");
                row.createCell(7).setCellValue(user.getPhone() != null ? user.getPhone() : "");
            }

            // 调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }

            // 将工作簿写入字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            workbook.close();

            // 设置响应头
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            httpHeaders.setContentDispositionFormData("attachment", "members.xlsx");

            return ResponseEntity.ok()
                    .headers(httpHeaders)
                    .body(outputStream.toByteArray());

        } catch (IOException e) {
            return ResponseEntity.badRequest().body(new byte[0]);
        }
    }
}
